using System;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
using Colman.Rpg.Connection;
using Colman.Rpg.Properties;

namespace Colman.Rpg
{
    ///<summary>
    /// Logi in Form
    ///</summary>
    public partial class LoginForm : Form
    {
        ///<summary>
        /// Initialize the Form ANd gets the last good login parameters 
        ///</summary>
        public LoginForm()
        {
            InitializeComponent();
            Settings st = new Settings();
            TbServerName.Text = st.ServerName;
            TbUserName.Text = st.UserName;
            this.Icon = Colman.Rpg.Properties.Resources.RpgIcon;
        }

        private void BtnOK_Click(object sender, EventArgs e)
        {
            try
            {
                //sending the log in parameters 
                ClientEndPoint.Initialize(TbServerName.Text, TbUserName.Text, GetMD5Checksum(mTbPassword.Text));
                this.DialogResult = DialogResult.OK;
                Settings st = new Settings();
                //Writing the User name and the Server Name to the app.config in the client 
                st.ServerName = TbServerName.Text;
                st.UserName = TbUserName.Text;
                st.Save();
                
                this.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message, this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void BtnCancel_Click(object sender, EventArgs e)
        {
            //Closing the program 
            this.Close();
        }

        ///<summary>
        /// Create the MD5 HASS Code  
        ///</summary>
        private static string GetMD5Checksum(string str)
        {
            // First we need to convert the string into bytes, which
            // means using a text encoder.
            Encoder enc = Encoding.Unicode.GetEncoder();

            // Create a buffer large enough to hold the string
            byte[] unicodeText = new byte[str.Length * 2];
            enc.GetBytes(str.ToCharArray(), 0, str.Length, unicodeText, 0, true);

            // Now that we have a byte array we can ask the CSP to hash it
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] result = md5.ComputeHash(unicodeText);

            // Build the final string by converting each byte
            // into hex and appending it to a StringBuilder
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < result.Length; i++)
            {
                sb.Append(result[i].ToString("X2"));
            }

            // And return it
            return sb.ToString();
        }

    }
}

